package day02;

/**
 * @author ZJX
 * @version 1.0
 * @descption 二分查找
 * @since 2025/10/12 20:21
 */
public class H {
    public int search(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        while (r >= l) {
            int mid = l + (r - l) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return -1;
    }

    public int mySqrt(int x) {
        if (x == 0 || x == 1) {
            return x;
        }
        int left = 1;
        int right = x;
        while (right >= left) {
            int mid = left + (right - left) / 2;
            if (mid == x / mid) {
                return mid;
            } else if (mid < x / mid) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return right;
    }

    public int[] searchRange(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        while (r >= l) {
            int mid = l + (r - l) / 2;
            if (nums[mid] == target) {
                int lm = mid - 1;
                int rm = mid + 1;
                while (lm >= 0 && nums[lm] == target) {
                    lm--;
                }
                while (rm <= nums.length - 1 && nums[rm] == target) {
                    rm++;
                }
                return new int[]{lm + 1, rm - 1};
            } else if (nums[mid] > target) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        return new int[]{-1, -1};
    }

    public int findMin(int[] nums) {
        int l = 0, r = nums.length - 1;
        while (r >= l) {
            int mid = l + (r - l) / 2;
            if (mid == r) break; // 避免无限循环
            if (nums[mid] >= nums[r]) {
                l = mid + 1;
            } else {
                r = mid; // 可能mid就是最小值
            }
        }
        return nums[l];
    }
}

